<script setup>
import {watchEffect, reactive, ref, watch} from "vue"
import {
  codeBtnLoading,
  codeBtnDisable,
  codeBtnText,
  getCode
} from '@/views/login/GetMailCode.js'
import {loginByMailAPI} from "@/api/login.js";
import {login} from "@/views/login/Login.js";
import {LOGIN_BY_PWD_ROUTE} from "@/router/routes/login/login.js";
import {useRouter, useRoute} from "vue-router";

const router = useRouter()
const route = useRoute()

// *****************
// * 登录相关数据限制 *
// *****************
const env = import.meta.env
const MAIL_MAX_LEN = Number.parseInt(env.VITE_MAIL_MAX_LEN) || 255
const CODE_LEN = Number.parseInt(env.VITE_CODE_LEN) || 6

// ***********
// * 登录信息 *
// ***********
const loginInfo = reactive({
  // mail: '1974498278@qq.com',
  // code: '299709'
  mail: '',
  code: '',
})

// **************
// * 登录按钮状态 *
// **************
const loginBtnLoading = ref(false)
const loginBtnDisable = ref(false)

// ******************
// * 监听登录信息的输入 *
// ******************
watchEffect(() => {
  if (loginInfo.mail.length <= 0) {
    codeBtnDisable.value = true
  } else {
    codeBtnDisable.value = false
  }
  if (loginInfo.mail.length <= 0 || loginInfo.code.length < CODE_LEN) {
    loginBtnDisable.value = true
  } else {
    loginBtnDisable.value = false
  }
})

// *******
// * 登录 *
// *******
function handleLogin() {
  login(
      loginBtnLoading,
      loginBtnDisable,
      () => {
        const res = loginByMailAPI(loginInfo.mail, loginInfo.code)
        return res
      },
      router,
      route
  )
}

const goLoginByPwd = () => {
  router.push({name: LOGIN_BY_PWD_ROUTE, query: {redirect: route.query.toRouteName}})
}
</script>

<template>
  <div class="login-by-mail glass-container mt-16 p-10 w-96">
    <div class="title text-gray-100 text-3xl">邮箱登录</div>
    <el-input
        class="mt-8"
        placeholder="请输入邮箱"
        clearable
        :maxlength="MAIL_MAX_LEN"
        v-model="loginInfo.mail"
    />
    <div class="mt-4 flex items-center">
      <el-input
          class=""
          :maxlength="CODE_LEN"
          show-word-limit
          clearable
          v-model="loginInfo.code"
          :placeholder="`请输入 ${CODE_LEN} 位验证码`"
      />
      <el-button
          class="w-32"
          type="primary"
          :disabled="codeBtnDisable"
          :loading="codeBtnLoading"
          @click="getCode(loginInfo.mail)"
          plain
      >{{ codeBtnText }}</el-button>
    </div>
    <div class="mt-4 flex justify-between items-center">
      <el-button
          class="w-24"
          type="primary"
          plain
          :disabled="loginBtnDisable"
          :loading="loginBtnLoading"
          @click="handleLogin"
      >登录</el-button>
      <span @click="goLoginByPwd" class="mr-4 p-1 cursor-pointer hover:text-blue-400">密码登录</span>
    </div>
  </div>
</template>

<style scoped>

</style>